package com.huaxinkai.mobile.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * 服务器端线程类
 * @author liuzh
 * @date 2017年1月14日下午11:12:21
 */
public class ServerThread extends Thread {
	//和本线程相关的线程
	Socket socket = null;
	
	public ServerThread(Socket socket){
		this.socket = socket;
	}
	
	//线程执行的操作，响应客户端的请求
	public void run(){
		InputStream is = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		OutputStream os= null;
		PrintWriter pw = null;
		try {
			//获取输入流，获取客户端信息
			is = socket.getInputStream();
			isr = new InputStreamReader(is);
			br = new BufferedReader(isr);
			String info = null;
			while( (info = br.readLine()) != null){
				System.out.println("我是服务器，客户端说：" + info);
			}
			socket.shutdownInput();//关闭输入流
			
			//获取输出流，用来响应
			os = socket.getOutputStream();
			pw = new PrintWriter(os);
			pw.write("欢迎您！！");
			pw.flush();
			
			
			//关闭资源
			pw.close();
			os.close();
			
			
			br.close();
			isr.close();
			is.close();
			socket.close();
			
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
		}
	}
}
